package com.chinackts.auth.repository.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Lianhong
 * @since 2021/10/27
 */
@Repository
public class LoginParamsRepository {

    @Resource
    private StringRedisTemplate redisTemplate1;

    private static final String KEY = "%s:login-pms";

    @Value("${e-port.redis.timeout}")
    private long timeout;

    /**
     * 获取登录参数
     *
     * @param id 用户标识
     */
    public JSONObject getLoginParams(String id) {
        ValueOperations<String, String> ops = this.redisTemplate1.opsForValue();
        String result = ops.get(String.format(KEY, id));
        if (StringUtils.isEmpty(result)) return null;
        return JSON.parseObject(result);
    }

    /**
     * 存储登录参数
     *
     * @param id 用户标识
     */
    public void saveLoginParams(String id, JSONObject params) {
        ValueOperations<String, String> ops = this.redisTemplate1.opsForValue();
        ops.set(String.format(KEY, id), params.toJSONString(), timeout, TimeUnit.HOURS);
    }
}
